<template>
  <div class="manage_container">
    <h2 class="title">脚本管理</h2>
    <el-divider></el-divider>
    <el-table :data="list" style="width: 100%" height="360">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="name" label="文件名" width="100" />
      <el-table-column prop="path" label="地址" />
      <el-table-column prop="operationNumber" label="操作数" width="80" />
      <el-table-column prop="executorTime" label="最大执行时间(ms)" width="120" />
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleRun(scope.row.path)">
            运行
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.path)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request.js'

const list = ref([])
const router = useRouter()

const updateList = async () => {
  const res = await request.post('/script/list')
  list.value = res.data.list
}
const handleDelete = async (path) => {
  try {
    await ElMessageBox.confirm('确认删除该脚本文件吗？无法找回！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    })
    const res = await request.post('/script/remove', {
      path: path,
    })
    updateList()
  } catch (error) {
    // 区分取消输入和请求错误
    if (error === 'cancel' || error === 'close') {
      ElMessage({
        type: 'info',
        message: '已取消输入',
      })
    } else updateList()
  }
}

const handleRun = async (path) => {
  await router.push({
    name: 'scriptRun',
    params: {
      path: path,
    },
  })
}

onMounted(() => {
  updateList()
})
</script>

<style lang="less" scoped>
@import url('../assets/main.less');

.manage_container {
  padding: 0px 24px;
  border-radius: 12px;

  .title {
    color: var(--el-text-color-primary);
    font-size: 1.5em;
    margin-bottom: 1em;
    position: relative;
    margin-top: 10px;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 50px;
      height: 3px;
      background: @primary-color;
    }
  }
}
</style>
